package com.xnyzc.lhy.resource.service.impl.amap;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xnyzc.lhy.common.component.amap.GouldMapUtils;
import com.xnyzc.lhy.common.entity.GouldLYResult;
import com.xnyzc.lhy.common.entity.TrackInfo;
import com.xnyzc.lhy.common.entity.UploadTrackInfo;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.order.entity.order.OaDOrder;
import com.xnyzc.lhy.mis.entity.user.OaDUser;
import com.xnyzc.lhy.order.entity.order.OaSysOrderDetails;
import com.xnyzc.lhy.order.entity.user.OaDUserInfo;
import com.xnyzc.lhy.resource.entity.amap.*;
import com.xnyzc.lhy.resource.mapper.worksheet.OaDOrderMapper;
import com.xnyzc.lhy.resource.mapper.worksheet.OaDUserMapper;
import com.xnyzc.lhy.resource.mapper.worksheet.OaSysOrderDetailsMapper;
import com.xnyzc.lhy.resource.mapper.worksheet.UserInfoMapper;
import com.xnyzc.lhy.resource.service.amap.IAmapService;
import com.xnyzc.lhy.resource.util.FalconServiceUtil;
import com.xnyzc.lhy.resource.util.GouldMapUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @author huxuekuo
 */
@Service
@Slf4j
public class AmapServiceImpl implements IAmapService {
    public static String serviceId;

    @Value("${global.amap.lyServiceId}")
    public void setServiceId(String amapServiceId) {
        serviceId = amapServiceId;
    }

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private OaDUserMapper oaDUserMapper;

    @Autowired
    private OaDOrderMapper orderMapper;

    @Autowired
    private OaSysOrderDetailsMapper oaSysOrderDetailsMapper;

    @Autowired
    UserInfoMapper oaDUserInfoMapper;

    /**
     * 获取猎鹰服务终端ID
     *
     * @param param
     * @return
     */
    @Override
    public Long getAmapTid(AmapTidParam param) {
        return FalconServiceUtil.addTerminalId(param);
    }

    /**
     * 逆地理编码
     *
     * @param location 经纬度起始|终到
     * @return
     */
    @Override
    public String getRegeo(String location) {
        return FalconServiceUtil.getRegeo(location);
    }

    /**
     * 获取猎鹰服务轨迹ID
     *
     * @param param
     * @return
     */
    @Override
    public Long getAmapGpdId(AmapGpsIdParam param) {
        return FalconServiceUtil.addGpsId(param);
    }

    @Override
    public Long getAmapGpdId(String sid, String tid) {
        return FalconServiceUtil.addGpsId(sid, tid);
    }

    @Override
    public Long getAmapTid(String serviceId, Long userId, String clientId, String tag) {
        return FalconServiceUtil.addTerminalId(serviceId, userId, clientId, tag);
    }

    /**
     * 获取两个点之间的距离
     *
     * @param startLng 开始经度
     * @param startLat 开始纬度
     * @param endLng   结束经度
     * @param endLat   结束纬度
     * @return
     */
    @Override
    public Double getDistance(String startLng, String startLat, String endLng, String endLat) {
        return GouldMapUtil.getDistance(startLng, startLat, endLng, endLat);
    }

    /**
     * 获取两个点之间的时间与距离(文字版)
     *
     * @param startPoint 开始点位
     * @param endPoint   结束点位
     * @return
     */
    @Override
    public HashMap<String, String> getDistanceAndDuration(String startPoint, String endPoint) {
        return GouldMapUtil.getDistanceAndDuration(startPoint, endPoint);
    }

    /**
     * 获取两个点之间的时间与距离(数字版)
     *
     * @param startPoint 开始点位
     * @param endPoint   结束点位
     * @return
     */
    @Override
    public Map<String, Integer> getStrategy(String startPoint, String endPoint) {
        return GouldMapUtil.getStrategy(startPoint, endPoint);
    }

    /**
     * 根据开始与结束时间获取历史轨迹
     *
     * @return
     */
    @Override
    public AmapGouldHistoryGps getHistoryGps(AmapHistoryGpsParam param) {
        return GouldMapUtil.historyGps(param.getServiceId(), param.getTid(), param.getGpsId(), param.getStartTime(), param.getEndTime(), param.getPage(),0);
    }

    /**
     * 删除轨迹信息
     * @param sid  服务ID
     * @param trid 轨迹ID
     * @param tid  终端ID
     * @return
     */
    @Override
    public Boolean deleteGpsHistorys(Long sid, Long trid, Long tid) {
        return GouldMapUtil.deleteGpsHistorys(sid, trid, tid);
    }

    /**
     * 获取两个点位之间的距离
     *
     * @param startPoint 开始点位
     * @param endPoint   结束点位
     * @return
     */
    @Override
    public AmapGouldResult getDistancePoint(String startPoint, String endPoint) {
        return GouldMapUtil.getDistance(startPoint, endPoint);
    }

    /**
     * 获取两个点位之间的直线距离
     *
     * @return
     */
    @Override
    public Integer getLineDistance(String startLng, String startLat, String endLng, String endLat) {
        return GouldMapUtil.getLineDistance(startLng, startLat, endLng, endLat);
    }

    @Override
    public boolean uploadTrackFromMongo(OaDOrder oaDOrder1) {
        OaDOrder oaDOrder = orderMapper.selectById(oaDOrder1.getOrderNo());
        String orderNo = oaDOrder.getOrderNo();
        QueryWrapper<OaSysOrderDetails> queryWrapperDetails = new QueryWrapper();
        queryWrapperDetails.eq(OaSysOrderDetails.ORDER_NO,oaDOrder1.getOrderNo());
        OaSysOrderDetails oaSysOrderDetails = oaSysOrderDetailsMapper.selectOne(queryWrapperDetails);

        //GouldMapUtil
        //出发时间
        Date departureTime = oaSysOrderDetails.getMeetCTime();
        //计价时间
        Date beginChargeTime = oaSysOrderDetails.getStartJourneyTime();
        //结束时间
        Date finishTime = oaSysOrderDetails.getEndJourneyTime();
        Query query=new Query();
        query.addCriteria(Criteria.where("orderNo").is(orderNo).and("operateTime").gte(departureTime).lte(beginChargeTime));
        //从司机出发到开始计价的轨迹
        List<TrackInfo> trackInfo1 = mongoTemplate.find(query, TrackInfo.class, "trackInfo");
        query=new Query();
        query.addCriteria(Criteria.where("orderNo").is(orderNo).and("operateTime").gte(beginChargeTime).lte(finishTime));
        //开始计价到订单结束
        List<TrackInfo> trackInfo2 = mongoTemplate.find(query, TrackInfo.class, "trackInfo");
        if (trackInfo1.size()<1 ){
            log.error("未查询到去接乘客轨迹数据，订单："+orderNo);
        }
        if (trackInfo2.size()<1){
            log.error("未查询到接到乘客后轨迹数据，订单："+orderNo);
        }
        //处理数据
        List<UploadTrackInfo> uploadTrackInfos1=new ArrayList<>();
        List<UploadTrackInfo> uploadTrackInfos2=new ArrayList<>();
        try{
            for (int i = 0; i < trackInfo1.size(); i++) {
                UploadTrackInfo uploadTrackInfo=new UploadTrackInfo();
                uploadTrackInfo.setLocatetime(trackInfo1.get(i).getOperateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
                uploadTrackInfo.setSpeed(trackInfo1.get(i).getSpeed());
                uploadTrackInfo.setLocation(trackInfo1.get(i).getLng()+","+trackInfo1.get(i).getLat());
                uploadTrackInfos1.add(uploadTrackInfo);
            }
            for (int i = 0; i < trackInfo2.size(); i++) {
                UploadTrackInfo uploadTrackInfo=new UploadTrackInfo();
                uploadTrackInfo.setLocatetime(trackInfo2.get(i).getOperateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
                uploadTrackInfo.setSpeed(trackInfo2.get(i).getSpeed());
                uploadTrackInfo.setLocation(trackInfo2.get(i).getLng()+","+trackInfo2.get(i).getLat());
                uploadTrackInfos2.add(uploadTrackInfo);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        /*QueryWrapper<OaDUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaDUser.DRIVER_ID,oaDOrder.getDriverId());
        OaDUser oaDUser = oaDUserMapper.selectOne(queryWrapper);*/
        QueryWrapper<OaDUserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(OaDUserInfo.DRIVER_ID,oaDOrder.getDriverId());
        OaDUserInfo oaDUserInfo=oaDUserInfoMapper.selectOne(queryWrapper);
        Long terminalId = oaDUserInfo.getTid();
        //创建轨迹id
        long uploadId=IDUtil.nextId();
        GouldLYResult result = GouldMapUtils.registTrace(serviceId, terminalId.toString(),  uploadId+ "_接乘客轨迹");
        GouldLYResult result2 = GouldMapUtils.registTrace(serviceId, terminalId.toString(), uploadId + "_开始计价轨迹");
        if ("10000".equals(result.getErrcode()) && "10000".equals(result2.getErrcode())){
            for (int i = 0; i < uploadTrackInfos1.size(); i+=100) {
                List<UploadTrackInfo> uploadData = new ArrayList<>();
                if (uploadTrackInfos1.size()-i<100){
                    uploadData=uploadTrackInfos1.subList(i,uploadTrackInfos1.size());
                }else {
                    uploadData = uploadTrackInfos1.subList(i, i + 100);
                }
                //上传轨迹
                GouldMapUtils.uploadTrackNew(Long.parseLong(serviceId),terminalId,result.getData().getTrid(),
                        JSON.toJSONString(uploadData));
            }
            for (int i = 0; i < uploadTrackInfos2.size(); i+=100) {
                List<UploadTrackInfo> uploadData = new ArrayList<>();
                if (uploadTrackInfos2.size()-i<100){
                    uploadData=uploadTrackInfos2.subList(i,uploadTrackInfos2.size());
                }else {
                    uploadData = uploadTrackInfos2.subList(i, i + 100);
                }
                //上传轨迹
                GouldMapUtils.uploadTrackNew(Long.parseLong(serviceId),terminalId,result2.getData().getTrid(),
                        JSON.toJSONString(uploadData));
            }
            String trackId=result.getData().getTrid()+","+result2.getData().getTrid();
            oaDOrder.setTrackId(trackId);
            orderMapper.updateById(oaDOrder);
        }else {
            log.error("创建轨迹失败："+orderNo);
            return false;
        }

        return true;
    }
}
